package com.Test;

import org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @version: 1.0
 * Create at:   2021-12-16 10:44:48
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 */
public class NonBlockingServer {
    private int port = 6584;
    private Selector selector;
    static RandomAccessFile raf = null;
    ThreadPoolExecutorFactoryBean factoryBean = new ThreadPoolExecutorFactoryBean();
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 5000, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), factoryBean);


    public NonBlockingServer() throws Exception {
        selector = Selector.open();
        createFile();

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(port));
        serverSocketChannel.configureBlocking(false);

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务启动成功");
    }

    public static void createFile() throws IOException {
        raf = new RandomAccessFile(new File("/Users/user/Documents/MyGIt/zlx-study-home/src/main/java/com/Test/ces.md"), "rw");

    }

    public void service() {
        while (true) {
            SelectionKey key = null;
            try {
                selector.select();
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    key = (SelectionKey) iterator.next();
                    iterator.remove();
                    if (key.isAcceptable()) {
                        // "接受连接就绪事件"的响应代码
                        ServerSocketChannel serverSocketChannel =
                                (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = serverSocketChannel.accept();

                        socketChannel.configureBlocking(false);
                        SelectionKey selectionKey =
                                socketChannel.register(selector, SelectionKey.OP_WRITE);
                        System.out.println(socketChannel.getRemoteAddress());
                    }
                    if (key.isWritable()) {
                        // "写就绪事件"的响应代码
                        SelectionKey finalKey = key;
                        this.threadPoolExecutor.execute(() -> {
                            SocketChannel socketChannel = null;
                            try {
                                socketChannel = (SocketChannel) finalKey.channel();
                                raf.seek(0);
                                byte[] b = new byte[64];
                                int hasRead = 0;
                                //循环读取文件
                                int i = 0;
                                while ((hasRead = raf.read(b)) > 0) {
                                    //输出文件读取的内容
                                    i++;
                                    socketChannel.write(ByteBuffer.wrap(b, 0, hasRead));
                                }
                                System.out.println("读取次数" + i);

                            } catch (IOException e) {
                                e.printStackTrace();
                            }finally {
                                try {
                                    socketChannel.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        key.cancel();
                    }
                }
            } catch (IOException e) {
                try {
                    key.channel().close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                key.cancel();
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new NonBlockingServer().service();


    }
}
